package com.lzc.springboot.controller;


import com.lzc.springboot.domain.ResultInfo;
import com.lzc.springboot.domain.User;
import com.lzc.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  private UserService userService;

  /**
   * 用户登录
   * @param user
   * @return
   */
  @RequestMapping("/login")
  public ResultInfo<User> login(@RequestBody User user, HttpServletResponse response){
    ResultInfo<User> login = userService.login(user);
    if (login.getCode() == 1){
      Cookie userName = new Cookie("username",login.getData().getUsername());
      Cookie passWord = new Cookie("password",login.getData().getPassword());
      response.addCookie(userName);
      response.addCookie(passWord);
    }
    return login;
  }

  /**
   * 根据cookie值查询用户
   * @param request
   * @return
   */
  @RequestMapping("/findUser")
  public ResultInfo<User> findUser(HttpServletRequest request){
    Cookie[] cookies = request.getCookies();
    User user = new User();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals("username")) user.setUsername(cookie.getValue());
      else if(cookie.getName().equals("password"))user.setPassword(cookie.getValue());
    }
    ResultInfo<User> resultInfo = userService.login(user);
    return resultInfo;
  }

  /**
   * 更改用户信息
   * @param user
   */
  @RequestMapping("/changeUser")
  public void changeUser(@RequestBody User user){
    userService.changeUser(user);
  }

  /**
   * 根据用户ID查询用户
   * @param id
   * @return
   */
  @RequestMapping(value = "/findUserById",method = RequestMethod.GET)
  public User findUserById(@RequestParam("id") int id){
    return userService.findUserById(id);
  }

  /**
   * 根据用户ID删除用户
   * @param id
   */
  @RequestMapping(value = "/delUserById", method = RequestMethod.GET)
  public void delUserById(@RequestParam("id") int id){
    userService.delUserById(id);
  }

  /**
   * 审核专家通过
   * @param id
   */
  @RequestMapping(value = "/expertChecked", method = RequestMethod.GET)
  public void expertChecked(@RequestParam("id") int id){
    userService.expertChecked(id);
  }

  /**
   * 审核专家未通过
   * @param id
   */
  @RequestMapping(value = "/expertUnChecked", method = RequestMethod.GET)
  public void expertUnChecked(@RequestParam("id") int id){
    userService.expertUnChecked(id);
  }

  /**
   * 用户注册
   * @param user
   */
  @RequestMapping("/register")
  public ResultInfo<User> register(@RequestBody User user){
    return userService.register(user);
  }
}
